﻿using Cms.Application.Admin.Views;
using Cms.Application.IO;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class ApplicationsPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly IApplicationsView _view;

        public IDiskAccess DiskAccess { get; set; }
        
        public ApplicationsPresenter(IApplicationsView view)
            : this(view, new RepositoryFactory())
        {
            DiskAccess = new DiskAccess();
        }

        public ApplicationsPresenter(IApplicationsView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.Applications)
                _view.RedirectToPermissionDeniedPage();
        }

        public void Initialize()
        {
            SetApplications();
        }
        
        public void SetApplications()
        {
            _view.SetApplications(_administrator.CurrentSite.Applications);
        }

        public void DeleteApplication(int id)
        {
            Domain.Application app = SiteRepository.GetApplication(id);
            if (app.Pages.Count == 0)
                PerformDelete(app);
            else
                _view.DisplayUnableToDeleteAlert(app.Name);
        }
        
        private void PerformDelete(Domain.Application app)
        {
            app.Site.Applications.Remove(app);
            app.Site = null;
            foreach (ApplicationPage ap in app.Pages)
            {
                ap.Application.Pages.Remove(ap);
                ap.Application = null;
                DiskAccess.DeleteFile("__System\\ApplicationPages\\" + app.ID + ".aspx");
            }
            app.Pages.Clear();
            SiteRepository.DeleteApplication(app);
            SiteRepository.SaveSite(_administrator.CurrentSite);
            SetApplications();
        }
    }
}